package com.yumingjaing.thread;

/**
 * @description: 线程暂停的方式
 * @author: John
 * @version: TestThreadStop.java, v1.0 2024年12月15日 07:05
 */
public class TestThreadStop {

    private static volatile boolean flag = false;

    public static void main(String[] args) throws InterruptedException {

//        t1();
        t2();
    }

    /**
     * 使用共享变量暂停线程
     */
    private static void t1() throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                int i = 1;
                while (!flag) {
                    if (i == 5) {
                        flag = true;
                    }
                    ++i;
                    System.out.println("====");
                }
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        thread.start();
        Thread.sleep(10000);
        System.out.println(thread.getState());
    }

    private static void t2() throws InterruptedException {
        // 线程默认情况下，    interrupt标记位：false
        System.out.println(Thread.currentThread().isInterrupted());
        // 执行interrupt之后，再次查看打断信息
        Thread.currentThread().interrupt();
        // interrupt标记位：ture
        System.out.println(Thread.currentThread().isInterrupted());
        // 返回当前线程，并归位为false interrupt标记位：ture
        System.out.println(Thread.interrupted());
        // 已经归位了
        System.out.println(Thread.interrupted());

        // =====================================================
        Thread t1 = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                // 处理业务
            }
            System.out.println("t1结束");
        });
        t1.start();
        Thread.sleep(500);
        t1.interrupt();
    }
}